package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.adapter.SelectionAdapter;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.CarlaClassicVo;
import com.jdy.haoduoaiteacher.model.CartoonVo;
import com.jdy.haoduoaiteacher.model.CategoryItem;
import com.jdy.haoduoaiteacher.model.HotSearchKey;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.pulltorefresh.PullToRefreshLayout;
import com.jdy.haoduoaiteacher.pulltorefresh.PullToRefreshLayout.OnRefreshListener;
import com.jdy.haoduoaiteacher.pulltorefresh.PullableGridView;
import com.jdy.haoduoaiteacher.util.ACache;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.LeConfig;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.view.RippleView;
import com.jdy.haoduoaiteacher.view.RippleView.OnRippleCompleteListener;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

//import com.jdy.haoduoaiteacher.R;

public class ChoiceActivity extends BaseActivity implements OnRefreshListener,
    OnItemClickListener {

  @InjectView(id = R.id.refresh_view)
  private PullToRefreshLayout pullToRefreshLayout;
  @InjectView(id = R.id.content_views)
  private PullableGridView gridView;

  @InjectView(id = R.id.emptylayout)
  private LinearLayout emptylayout;
  @InjectView(id = R.id.reloadRippleView)
  private RippleView reloadRippleView;

  private SelectionAdapter storyListAdapter;

  private CategoryItem categoryItem = null;
  private HotSearchKey searchKey = null;
  private int mLastpage = 1;
  private ArrayList<CartoonVo> mAdapterList = null;
  private ArrayList<CartoonVo> mArrayList = null;
  public boolean isrefreshlist = false;
  private LeUser leUser;
  private String title;
  private String key;
  private ACache mCache;
  private JSONArray jsonArr;

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.choice);
    initialize();
    initlistener();
    requestData(true, true);
  }

  private String searchType;

  private void initialize() {
    mCache = ACache.get(this);

    Intent intent = getIntent();
    if (intent.getSerializableExtra("categoryitem") != null) {
      categoryItem = (CategoryItem) intent.getSerializableExtra("categoryitem");
      title = categoryItem.name;
    } else if (intent.getSerializableExtra("searchkey") != null) {
      searchKey = (HotSearchKey) intent.getSerializableExtra("searchkey");
      title = searchKey.name;
      key = title;
    } else {
      key = getIntent().getStringExtra("key");
      title = key;
    }

    searchType = getIntent().getStringExtra("searchType");

    setTitle(title);
    mAdapterList = new ArrayList<>();
    mArrayList = new ArrayList<>();
    leUser = MyTeacherApp.getInstance().getUserTeacher();
  }

  private void initlistener() {
    gridView.setOnItemClickListener(this);
    reloadRippleView
        .setOnRippleCompleteListener(new OnRippleCompleteListener() {
          @Override
          public void onComplete(RippleView rippleView) {
            mLastpage = 1;
            isrefreshlist = true;
            requestData(true, false);
          }
        });
    pullToRefreshLayout.setOnRefreshListener(this);
  }

  private void requestData(boolean isShowLoading, boolean isFromCache) {
    if (isShowLoading) {
      showloading("加载中..");
    }

    if (Tools.isEmpty(searchType) && isFromCache) {
      jsonArr = mCache.getAsJSONArray(title);
    }

    if (jsonArr != null && jsonArr.length() > 0 && isFromCache) {
      dismissLoading();
      try {
        if (mAdapterList != null) {
          mAdapterList.clear();
        }
        if (isrefreshlist) {
          mArrayList.clear();
        }
        for (int i = 0; i < jsonArr.length(); i++) {
          JSONObject obj = ((JSONObject) jsonArr.opt(i));

          if (Tools.isNotEmpty(obj.toString())) {
            CartoonVo itemVo = JsonSerializer.getInstance().deserialize(
                obj.toString(), CartoonVo.class);
            mAdapterList.add(itemVo);
          }

        }
      } catch (Exception e) {
      }
      mArrayList.addAll(mAdapterList);
      setView();
    } else {

      if (Tools.isNotEmpty(searchType)) {
        new CustomAsyncTask(ChoiceActivity.this, new IAsyncTask() {
          @Override
          public void onRecieveData(Activity activity, ResponseResult result) {
            dismissLoading();
            if (result.isSuccess()) {
              try {
                JSONObject json = new JSONObject(result.data);
                String data = json.optString("data");
                final JSONArray array = new JSONArray(data);

                if (mAdapterList != null) {
                  mAdapterList.clear();
                }
                if (isrefreshlist) {
                  mArrayList.clear();
                }
                for (int i = 0; i < array.length(); i++) {
                  JSONObject obj = ((JSONObject) array.opt(i));
                  if (Tools.isNotEmpty(obj.toString())) {
                    CartoonVo itemVo = JsonSerializer.getInstance()
                        .deserialize(obj.toString(), CartoonVo.class);
                    if (Tools.isNotEmpty(itemVo.catalog)
                        && !itemVo.catalog.contains("book")) {
                      mAdapterList.add(itemVo);
                    }

                  }

                }
              } catch (Exception e) {
              }
              mArrayList.addAll(mAdapterList);
              setView();
            } else {
              toastShow(result.data.toString());
              pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
              pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
            }
          }

          @Override
          public ResponseResult doInbackground(Activity activity) {
            if (leUser == null) {
              leUser = Tools.restoreLeUser();
            }

            HashMap<String, Object> param_ = new HashMap<String, Object>();
            param_.put(HttpUtils.TAG_SNO_I, leUser.sno);
            if (Tools.isNotEmpty(searchKey)) {
              param_.put("name", searchKey.name);
            } else {
              param_.put("name", key);
            }

            param_.put("page", mLastpage);
            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

            if (searchType.contains("album")) {
              return HttpUtils.startRequest(HttpUtils.HOST_API
                  + HttpUtils.GET_CATALOG_ALBUM, param_,
                  HttpUtils.TAG_GET_REQUEST);
            } else {
              return HttpUtils
                  .startRequest(HttpUtils.HOST_API + HttpUtils.GET_STORY_LIST,
                      param_, HttpUtils.TAG_GET_REQUEST);
            }

          }
        }).execute();

      } else {

        new CustomAsyncTask(ChoiceActivity.this, new IAsyncTask() {
          @Override
          public void onRecieveData(Activity activity, ResponseResult result) {
            dismissLoading();
            if (result.isSuccess()) {

              try {
                JSONObject json = new JSONObject(result.data);
                String data = json.optString("data");
                final JSONArray array = new JSONArray(data);

                new Thread() {
                  @Override
                  public void run() {
                    if (jsonArr != null) {
                      mCache.remove(title);
                    }
                    mCache.put(title, array);
                  };
                }.start();

                if (mAdapterList != null)
                  mAdapterList.clear();
                if (isrefreshlist) {
                  mArrayList.clear();
                }
                for (int i = 0; i < array.length(); i++) {
                  JSONObject obj = ((JSONObject) array.opt(i));

                  if (Tools.isNotEmpty(obj.toString())) {
                    CartoonVo itemVo = JsonSerializer.getInstance()
                        .deserialize(obj.toString(), CartoonVo.class);
                    mAdapterList.add(itemVo);
                  }

                }
              } catch (Exception e) {
              }
              mArrayList.addAll(mAdapterList);
              setView();
            } else {
              toastShow(result.data.toString());
              pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
              pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
            }
          }

          @Override
          public ResponseResult doInbackground(Activity activity) {
            if (leUser == null) {
              leUser = Tools.restoreLeUser();
            }

            HashMap<String, Object> param_ = new HashMap<String, Object>();
            param_.put(HttpUtils.TAG_SNO_I, leUser.sno);
            if (categoryItem != null) {
              param_.put("category_id", categoryItem.id);
            } else if (searchKey != null) {
              param_.put("name", key);
            } else {
              param_.put("name", key);
            }

            param_.put("page", mLastpage);
            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
            return HttpUtils.startRequest(HttpUtils.HOST_API
                + HttpUtils.GET_CATALOG_ALBUM, param_,
                HttpUtils.TAG_GET_REQUEST);
          }
        }).execute();
      }
    }
  }

  private void setView() {
    if (storyListAdapter == null) {
      storyListAdapter = new SelectionAdapter(ChoiceActivity.this, mArrayList);
      gridView.setAdapter(storyListAdapter);
    } else {
      storyListAdapter.notifyDataSetChanged();
      pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
      // pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }
    if (storyListAdapter.getCount() == 0) {
      emptylayout.setVisibility(View.VISIBLE);
    } else {
      emptylayout.setVisibility(View.GONE);
    }
  }

  private CarlaClassicVo convert2CarlaClassicVo(CartoonVo recommendStroy) {

    if (recommendStroy == null)
      return null;
    CartoonVo lhr = recommendStroy;
    CarlaClassicVo ccv = new CarlaClassicVo();
    // ccv.setId(lhr.getId());
    // ccv.setCategory_id(lhr.getCategory_id());
    // ccv.setCatalog(lhr.getCatalog());
    // ccv.setName(lhr.getName());
    // ccv.setCover(lhr.getCover());
    // ccv.setUrl(lhr.getUrl());
    // ccv.setEnabled(lhr.getEnabled());
    // ccv.setSort(lhr.getSort());
    // ccv.setLength(lhr.getLength());
    // ccv.setAgefrom(0);
    // ccv.setAgeto(0);
    // ccv.setLines(lhr.getLines());
    // ccv.setCreated_at(lhr.getCreated_at());
    // ccv.setUpdated_at(lhr.getUpdated_at());
    // ccv.setDeleted_at(lhr.getDeleted_at());
    // ccv.setFollowers(lhr.getFollowers());
    // ccv.setCorner_icon(lhr.getCorner_icon());
    // ccv.setAuthor(lhr.getAuthor());
    // ccv.setTags(lhr.getTags());

    ccv.id = lhr.id; // );
    ccv.category_id = lhr.category_id; // );
    ccv.catalog = lhr.catalog; // );
    ccv.name = lhr.name; // );
    ccv.cover = lhr.cover;// );
    ccv.url = lhr.url;// );
    ccv.enabled = lhr.enabled; // );
    ccv.sort = lhr.sort; // );
    ccv.length = lhr.length; // );
    ccv.agefrom = 0; // );
    ccv.ageto = 0;
    ccv.lines = lhr.lines; // );
    ccv.created_at = lhr.created_at; // );
    ccv.updated_at = lhr.updated_at; // );
    ccv.deleted_at = lhr.deleted_at; // );
    ccv.followers = lhr.followers;// );
    ccv.corner_icon = lhr.corner_icon; // );
    ccv.author = lhr.author; // );
    ccv.tags = lhr.tags; // );

    return ccv;
  }

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position,
      long id) {
    CartoonVo vo = mArrayList.get(position);
    Intent intent = new Intent();
    if (title.equals("宝宝电台")) {
      intent.setClass(this, RadioDetailActivity.class);
    } else {
      intent.setClass(this, StoryDetailActivity.class);
    }

    if (Tools.isNotEmpty(searchType)) {
      if (searchType.contains("story")) {
        if (vo.catalog.contains("dub")) {
          if (vo.category_id.contains("36")) { // 绘本
            // intent.setClass(this, StoryBookActivity.class);
            // Bundle bundle = new Bundle();
            // bundle.putSerializable("illustratedstory", vo);
            // intent.putExtras(bundle);
            // startActivity(intent);
          } else { // 故事
//            Bundle bundle = new Bundle();
//            bundle.putSerializable("carlaclassic", convert2CarlaClassicVo(vo));
//            intent.putExtras(bundle);
//            intent.setClass(this, RecordActivity.class);
//            startActivity(intent);
          }

          return;
        }
      } else {
        intent.setClass(this, StoryDetailActivity.class);
      }
    }

    intent.putExtra("id", vo.id);
    startActivity(intent);
  }

  @SuppressWarnings("unused")
  private void playvideo(final int sid, final String status) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          toastShow("已推送到设备播放");
//          if (LeConfig.isDeviceConnect) {
//            toastShow("已推送到设备播放");
//          } else {
//            toastShow("未连接到设备，请检查设备联网情况！");
//          }
        } else {
          if (Tools.isNotNullStr(result.data)) {
            toastShow(result.data);
          }
        }

        // if (result.isSuccess()) {
        // // if (("cartoon").equals(status) || ("continue").equals(status)) {
        // // toastShow("推送成功");
        // // isPlay = true;
        // // // playbutton.setBackgroundResource(R.drawable.pause_icon);
        // // } else if (("pause").equals(status)) {
        // // toastShow("暂停播放");
        // // isPlay = false;
        // // // playbutton.setBackgroundResource(R.drawable.ico_play);
        // // } else {
        // // toastShow(result.data);
        // // }
        // } else {
        // toastShow(result.data);
        // }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        HashMap<String, Object> param_ = new HashMap<String, Object>();

        int uid = -1, volume = -1, minutes = -1;
        param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_ACTION_I, "play");
        param_.put(HttpUtils.TAG_OPERATION_I, "cartoon");
        param_.put(HttpUtils.TAG_TYPE_I, "cartoon");
        param_.put("mode", "im");

        if (sid != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
        }

        param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  @Override
  public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
    mLastpage = 1;
    isrefreshlist = true;

    if (mCache != null) {
      mCache.remove(title);
    }

    requestData(false, false);
  }

  @Override
  public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
    mLastpage++;
    isrefreshlist = false;
    requestData(false, false);
  }
}
